package com.happy3w.ssp.schoolmatehome.repository;

import com.happy3w.ssp.schoolmatehome.service.user.UserStateSummary;
import lombok.RequiredArgsConstructor;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

@RequiredArgsConstructor
@Repository
public class UserStateRepository {
    private final JdbcTemplate jdbcTemplate;

    public UserStateSummary findById(Long userId) {
        UserStateSummary summary = jdbcTemplate.queryForObject(
                """
                        SELECT sum(ns.view_count) as view_count,
                        sum(ns.favorite_count) as favorite_count,
                        sum(ns.collect_count) as collect_count,
                        count(1) as note_count
                        FROM note n
                        left join note_state ns on n.id =ns.note_id\s
                        where n.owner_id=?""",
                BeanPropertyRowMapper.newInstance(UserStateSummary.class),
                userId);
        if (summary == null) {
            summary = new UserStateSummary();
        }

        Integer fansCount = jdbcTemplate.queryForObject("select count(1) from follow_state where user_id=?",
                Integer.class, userId);
        summary.setFansCount(fansCount == null ? 0 : fansCount);

        return summary;
    }
}
